import {
  addSysDictItem,
  deleteTargetLibType,
  deleteTargetLib,
  editDictItemByCode,
  selectTargetLibByPage,
  selectTargetLibTypeByTypeCode
} from '@/api/targetLib'
import {CCard} from '@/components/card'
import {CnMediumP, CnMediumSpan, CnNormalP, CnNormalSpan} from '@/components/text'
import {useTableLoading, useTablePaging} from '@/hooks/tableHook'
import {throttle} from '@/libs/debounce'
import {ant_design_vue} from '@/libs/global/antDesignVue'
import {toAddTargetToLib, toEditTargetToLib} from '@/libs/pageRedirect'
import {unReplaceBreak} from '@/libs/toolkit'
import {defineComponent, reactive, computed, watch, onMounted} from 'vue'
const {message} = ant_design_vue
type TableData = PmTargetLib.TargetLibData & {
  key: number
}
export default defineComponent({
  name: 'targetLib',
  setup(props, ctx) {
    // const {selectedRowKeys, rowSelection} = useTableSelectedRow()

    const {page, changePage, size, changeTableTotal, getPagination} = useTablePaging({
      page: 1,
      size: 10
    })
    const {loading, startLoading, closeLoading} = useTableLoading()
    let state = reactive<{
      targetLibName: string | undefined
      targetLibTypeCode: string | undefined
      targetLibTypes: Dict.Item<'007', string>[]
      dataSource: TableData[]
      addPmDimensionTypeVisible: boolean
      addPmDimensionTypeName: string
      editPmDimensionTypeVisible: boolean
      editPmDimensionTypeName: string
    }>({
      targetLibTypeCode: undefined,
      targetLibName: undefined,
      targetLibTypes: [],
      dataSource: [],
      addPmDimensionTypeVisible: false,
      addPmDimensionTypeName: '',
      editPmDimensionTypeVisible: false,
      editPmDimensionTypeName: ''
    })

    const tableColumns: CColumn<PmTargetLib.TargetLibData>[] = [
      {
        title: '名称',
        dataIndex: 'targetLibName',
        width: 180,
        ellipsis: true
      },
      {
        title: '指标类型',
        dataIndex: 'pmDimensionTypeName',
        width: 120,
        ellipsis: true
      },
      {
        title: '考核标准',
        dataIndex: 'targetLibStand',
        ellipsis: true
      },
      {
        title: '自评模板',
        dataIndex: 'selfContentTem',
        ellipsis: true
      },
      {
        title: '权重',
        dataIndex: 'targetLibWeight',
        width: 80,
        ellipsis: true
      },
      {
        title: '指标编码',
        dataIndex: 'targetLibCode',
        ellipsis: true
      },
      {
        title: '操作',
        dataIndex: 'utils',
        width: 144
      }
    ]

    const currentPmDimensionType = computed(() => {
      let current = state.targetLibTypes.filter(item => item.dictCode === state.targetLibTypeCode)
      return current && current.length ? current[0] : null
    })

    watch(
      () => state.targetLibTypeCode,
      n => {
        state.editPmDimensionTypeName = currentPmDimensionType.value?.dictName || ''
      }
    )

    function getPageData() {
      selectTargetLibTypeByTypeCode()
        .then(res => {
          state.targetLibTypes = res.data
          let oldTargetLibType =
            res.data.filter(item => item.dictCode === state.targetLibTypeCode)[0]?.dictCode ||
            undefined
          state.targetLibTypeCode = oldTargetLibType
          // if()
          console.log(state.targetLibTypes)
        })
        .catch(res => {})
      getTableData()
    }

    function getTableData() {
      startLoading()
      selectTargetLibByPage({
        page: page.value,
        size: size.value,
        targetLibName: state.targetLibName,
        targetLibTypeCode: state.targetLibTypeCode
      })
        .then(res => {
          res.data.list.forEach(item => {
            if (item.selfContentTem == undefined || item.selfContentTem == null) {
              item.selfContentTem = ''
            }
          })
          state.dataSource = res.data.list.map((item, idx) =>
            Object.assign({key: item.targetLibId}, item)
          )
          changeTableTotal(res.data.total)
          closeLoading()
        })
        .catch(err => {
          closeLoading()
        })
    }

    const searchInput = throttle(() => {
      if (page.value !== 1) {
        changePage(1)
      }
      getTableData()
    }, 300)

    function handleAddPmDimensionTypeOk() {
      state.addPmDimensionTypeVisible = false
      addSysDictItem({
        dictName: state.addPmDimensionTypeName
      })
        .then(res => {
          state.addPmDimensionTypeName = ''
          getPageData()
        })
        .catch(err => {})
    }

    function handleEditPmDimensionTypeOk() {
      if (!state.targetLibTypeCode) return
      editDictItemByCode({
        dictCode: state.targetLibTypeCode,
        dictName: state.editPmDimensionTypeName
      })
        .then(res => {
          getPageData()
        })
        .catch(err => {})

      state.editPmDimensionTypeVisible = false
    }

    function handleDelPmDimensionType(dictCode: string) {
      deleteTargetLibType({
        dictCode
      })
        .then(res => {
          state.targetLibTypeCode = undefined
          getPageData()
        })
        .catch(err => {})
    }

    function handleDeleteTargetClick(targetLibId: number) {
      deleteTargetLib({targetLibId})
        .then(res => {
          getPageData()
        })
        .catch(err => {
          if (err) {
            console.log(err)
            message.error({
              content: err.msg
            })
          }
        })
    }

    onMounted(() => {
      getPageData()
    })

    return () => (
      <CCard class='p-24 CBC-bg-toRight' title='指标库' showTitle={false}>
        <div class='flex items-start gap-x-16'>
          {/* 指标类型筛选区 */}
          <CCard
            title='指标类型'
            showTitle={false}
            showShadow={false}
            class='w-244 h-724 overflow-y-auto p-0 flex flex-col'
          >
            {/* 指标分类 */}
            <div class='w-full h-50 bg-infoLight border-b-1 border-cardLine flex items-center justify-between px-12'>
              <CnMediumSpan class='text-16'>指标分类</CnMediumSpan>
              <i
                class='iconfont icon-jiahao1 text-14 cursor-pointer'
                onClick={() => {
                  state.addPmDimensionTypeVisible = true
                }}
              ></i>
            </div>
            <div class='flex-1 overflow-y-auto'>
              <div
                class={[
                  'p-16 pr-32 truncate',
                  state.targetLibTypeCode === undefined ? 'bg-primaryLight' : ''
                ]}
                style={{
                  color: '#505559'
                }}
                row-selection='rowSelection'
                title='全部指标'
                onClick={() => {
                  state.targetLibTypeCode = undefined
                  getPageData()
                }}
              >
                全部指标
              </div>
              {/* 指标类别 */}
              {state.targetLibTypes.map((item, idx) => (
                <div
                  class={[
                    'p-16 pr-32 truncate cursor-pointer relative text-12',
                    state.targetLibTypeCode === item.dictCode ? 'bg-primaryLight' : ''
                  ]}
                  style={{
                    color: '#505559'
                  }}
                  title={item.dictName}
                  onClick={() => {
                    state.targetLibTypeCode = item.dictCode
                    getPageData()
                  }}
                >
                  {item.dictName}
                  {state.targetLibTypeCode === item.dictCode ? (
                    <div class='absolute right-8 bottom-1/2 -transform translate-y-1/2 flex items-center gap-x-8'>
                      <i
                        class='iconfont icon-xiugai text-13 hover:text-primary'
                        title='修改分类'
                        onClick={() => {
                          state.editPmDimensionTypeVisible = true
                        }}
                      ></i>
                      <a-popconfirm
                        v-slots={{
                          title: () => (
                            <div>
                              <CnMediumP>确认删除此指标分类？</CnMediumP>
                              <CnMediumP>删除指标分类时，分类下面所有指标都会删除</CnMediumP>
                            </div>
                          )
                        }}
                        ok-text='是'
                        cancel-text='否'
                        onConfirm={() => {
                          handleDelPmDimensionType(item.dictCode)
                        }}
                      >
                        <i
                          class='iconfont icon-shanchu text-13  hover:text-primary'
                          title='删除分类'
                        ></i>
                      </a-popconfirm>
                    </div>
                  ) : null}
                </div>
              ))}
            </div>
          </CCard>
          <div class='flex-1'>
            <div class='flex items-center justify-between mb-12'>
              <div class='flex items-center gap-x-8'>
                {/* <a-button class='rounded-4'>筛选</a-button> */}
                <a-input
                  class='w-full rounded-4'
                  placeholder='根据指标名称或编码搜索'
                  v-slots={{
                    prefix: () => <i class='iconfont icon-fangdajing text-infoHalf text-13'></i>
                  }}
                  v-model={[state.targetLibName, 'value']}
                  onInput={searchInput}
                ></a-input>
              </div>
              <div class='flex items-center gap-x-8'>
                <a-button
                  type='primary'
                  class='rounded-4'
                  onClick={() => {
                    toAddTargetToLib()
                  }}
                >
                  新增指标
                </a-button>
                {/* <a-button class='rounded-4'>删除</a-button> */}
              </div>
            </div>
            {/* 指标库表格区 */}
            <a-table
              class=''
              scroll={{y: 591}}
              pagination={getPagination({
                getTableData
              })}
              bordered
              dataSource={state.dataSource}
              columns={tableColumns}
              loading={loading.value}
            >
              {{
                bodyCell: ({text, record, index, column}: CBodyCell<TableData>) => {
                  switch (column.dataIndex) {
                    case 'utils':
                      return (
                        <div class=' flex items-center gap-x-8'>
                          <CnNormalSpan
                            class='text-primary cursor-pointer text-12'
                            onClick={() => {
                              toEditTargetToLib({
                                targetLibId: record.targetLibId
                              })
                            }}
                          >
                            编辑
                          </CnNormalSpan>
                          <a-popconfirm
                            v-slots={{
                              title: () => <CnMediumP>确认删除此指标？</CnMediumP>
                            }}
                            ok-text='是'
                            cancel-text='否'
                            onConfirm={() => {
                              handleDeleteTargetClick(record.targetLibId)
                            }}
                          >
                            <CnNormalSpan class='text-primary cursor-pointer text-12'>
                              删除
                            </CnNormalSpan>
                          </a-popconfirm>
                        </div>
                      )
                    case 'targetLibName':
                      return (
                        <a-tooltip title={text}>
                          <CnNormalP
                            class='text-12'
                            style={{
                              whiteSpace: 'break-spaces'
                            }}
                            onDblclick={() => {
                              toEditTargetToLib({
                                targetLibId: record.targetLibId
                              })
                            }}
                          >
                            {text}
                            {record.isBonus === 1 ? (
                              <CnNormalSpan class='text-primary'>（加分项）</CnNormalSpan>
                            ) : null}
                          </CnNormalP>
                        </a-tooltip>
                      )
                    default:
                      const str = unReplaceBreak(text + '')
                      return (
                        <a-tooltip title={str}>
                          <CnNormalP
                            class='text-12'
                            style={{
                              whiteSpace: 'break-spaces'
                            }}
                            onDblclick={() => {
                              toEditTargetToLib({
                                targetLibId: record.targetLibId
                              })
                            }}
                          >
                            {str}
                          </CnNormalP>
                        </a-tooltip>
                      )
                  }
                }
              }}
            </a-table>
          </div>
        </div>
        <a-modal
          title='添加指标分类'
          v-model={[state.addPmDimensionTypeVisible, 'visible']}
          onCancel={() => {
            console.log(1)

            state.addPmDimensionTypeVisible = false
            state.addPmDimensionTypeName = ''
          }}
          onOk={handleAddPmDimensionTypeOk}
        >
          <div class='mt-24'>
            <a-form-item label='分类名称'>
              <a-input
                placeholder='输入名称'
                class='w-3/4'
                v-model={[state.addPmDimensionTypeName, 'value']}
              ></a-input>
            </a-form-item>
          </div>
        </a-modal>
        <a-modal
          title='修改指标分类'
          v-model={[state.editPmDimensionTypeVisible, 'visible']}
          onCancel={() => {
            state.editPmDimensionTypeVisible = false
            state.editPmDimensionTypeName = ''
          }}
          onOk={handleEditPmDimensionTypeOk}
        >
          <div class='mt-24'>
            <a-form-item label='分类名称'>
              <a-input
                placeholder='输入名称'
                class='w-3/4'
                v-model={[state.editPmDimensionTypeName, 'value']}
              ></a-input>
            </a-form-item>
          </div>
        </a-modal>
      </CCard>
    )
  }
})
